import json
import uuid

from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from dwebsocket import accept_websocket

from apps.business import models
from django.core.paginator import Paginator
from django.core.cache import cache
from apps.business.models import Customers_poll_model,Customers_edit_model
from apps.config.models import Menu_model
from apps.config.serializers import Menu_serializer


# 获得主页，这里需要去获得角色拥有的权限
from apps.message.singal import action
from apps.users.models import Users_model

# list页面操作权限集合
def poll_view(request):
    # 后期这里可能要去数据库查询其拥有的权限
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'customers/list.html', {'data':menu_obj.data})
# 默认获得所有数据
def poll_list(request):
    try:
        cus_list = models.Customers_poll_model.objects.all()
        cus_count = models.Customers_poll_model.objects.count()
    except Exception as e:
        return JsonResponse({'code':201, 'msg':e})
    list = []
    for i in cus_list:
        # 获取当前账户的id
        if i.cus_created_person_id == request.user.id:
            dict = {}
            dict['id'] = i.id
            dict['cus_code'] = i.cus_code
            dict['cus_audited_object'] = i.cus_audited_object
            dict['cus_marital'] = i.get_cus_marital_display()
            dict['cus_entrust_code'] = i.cus_entrust_code
            dict['cus_entrust_name'] = i.cus_entrust_name
            dict['cus_cooperation_code'] = i.cus_cooperation_code
            dict['cus_cooperation_name'] = i.cus_cooperation_name
            dict['cus_address'] = i.cus_address
            dict['cus_phone'] = i.cus_phone
            dict['cus_create_person'] = i.cus_created_person.username
            dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
            dict['now_status'] = i.now_status
            dict['remark_describe'] = i.remark_describe
            list.append(dict)
        else:
            dict1 = {}
            dict1['id'] = i.id
            dict1['cus_code'] = i.cus_code
            dict1['cus_audited_object'] = i.cus_audited_object
            dict1['cus_marital'] = i.get_cus_marital_display()
            dict1['cus_entrust_code'] = i.cus_entrust_code
            dict1['cus_entrust_name'] = i.cus_entrust_name
            dict1['cus_cooperation_code'] = i.cus_cooperation_code
            dict1['cus_cooperation_name'] = i.cus_cooperation_name
            dict1['cus_address'] = i.cus_address
            dict1['cus_phone'] = i.cus_phone
            dict1['cus_create_person']=None
            dict1['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
            dict1['now_status'] = i.now_status
            dict1['remark_describe'] = i.remark_describe
            list.append(dict1)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code':0, 'mes':'成功！', 'count':cus_count, 'data':res}
    return JsonResponse(Result)
# 添加页面
def poll_insert_view(request):
    return render(request, 'customers/insert.html')

# 添加动作
@transaction.atomic
def poll_insert(request):
    # 进来应该先判断当前是否拥有添加权限
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '100101' not in per_list:
        return JsonResponse({'code':201,'msg':'您无此权限,请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('cus_code')
    audited_object = request.POST.get('cus_audited_object')
    marital = request.POST.get('cus_marital')
    phone = request.POST.get('cus_phone')
    entrust_code = request.POST.get('cus_entrust_code')
    entrust_name = request.POST.get('cus_entrust_name')
    cooperation_code = request.POST.get('cus_cooperation_code')
    cooperation_name = request.POST.get('cus_cooperation_name')
    address = request.POST.get('cus_address')
    created_person = request.user
    try:
        Customers_poll_model.objects.create(cus_code=code,cus_audited_object=audited_object,cus_marital=marital,cus_phone=phone,cus_entrust_code=entrust_code,
                                        cus_entrust_name=entrust_name,cus_cooperation_code=cooperation_code,cus_cooperation_name=cooperation_name,
                                        cus_address=address,cus_created_person=created_person)
    except Exception as aaa:
        if aaa.args[0]==1406:
            transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
            return JsonResponse({'code':201, 'msg':'数据过长！'})
        if aaa.args[0]==1062:
            transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
            return JsonResponse({'code':202, 'msg':'唯一值出现重复！请检查客户代码。'})
        else:
            transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code':0, 'msg':'添加成功！'})

# 修改页面
def poll_edit_view(request):
    return render(request, 'customers/edit.html')

@transaction.atomic
def poll_edit(request,id):
    # 先得判断是否具有添加权限（100102）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '100102' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('cus_code')
    name = request.POST.get('cus_audited_object')
    address = request.POST.get('cus_address')
    status = request.POST.get('now_status')
    remark = request.POST.get('remark_describe')
    try:
        cus_obj=Customers_poll_model.objects.get(pk=id)
        cus_obj.cus_code = code
        cus_obj.cus_audited_object = name
        cus_obj.cus_address = address
        cus_obj.now_status = status
        cus_obj.remark_describe = remark
        cus_obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code':202,'msg':'customers修改模块出现问题，请联系管理员'})
    return JsonResponse({'code': 0, 'msg': '更新成功！'})

# 查询
def poll_search(request):
    name = request.GET.get('searchname')
    try:
        if len(name) == 0:
            cus_list = models.Customers_poll_model.objects.filter()
        else:
            # 支持用户名/雇员代码/邮箱/手机号模糊查询
            cus_list = models.Customers_poll_model.objects.filter(
                Q(cus_audited_object__contains=name) | Q(cus_code__contains=name) | Q(cus_cooperation_name__contains=name) | Q(
                    cus_entrust_name__contains=name))
        count = len(list(cus_list))
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'business单查模块出现问题，请联系管理员！'})
    list1 = []
    for i in cus_list:
        if i.cus_created_person_id == request.user.id:
            dict = {}
            dict['id'] = i.id
            dict['cus_code'] = i.cus_code
            dict['cus_audited_object'] = i.cus_audited_object
            dict['cus_marital'] = i.get_cus_marital_display()
            dict['cus_entrust_code'] = i.cus_entrust_code
            dict['cus_entrust_name'] = i.cus_entrust_name
            dict['cus_cooperation_code'] = i.cus_cooperation_code
            dict['cus_cooperation_name'] = i.cus_cooperation_name
            dict['cus_address'] = i.cus_address
            dict['cus_phone'] = i.cus_phone
            dict['cus_create_person'] = list(models.Users_model.objects.filter(id=i.cus_created_person_id).values_list('username',flat=True))
            dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
            dict['now_status'] = i.now_status
            dict['remark_describe'] = i.remark_describe
            list1.append(dict)
        else:
            dict1 = {}
            dict1['id'] = i.id
            dict1['cus_code'] = i.cus_code
            dict1['cus_audited_object'] = i.cus_audited_object
            dict1['cus_marital'] = i.get_cus_marital_display()
            dict1['cus_entrust_code'] = i.cus_entrust_code
            dict1['cus_entrust_name'] = i.cus_entrust_name
            dict1['cus_cooperation_code'] = i.cus_cooperation_code
            dict1['cus_cooperation_name'] = i.cus_cooperation_name
            dict1['cus_address'] = i.cus_address
            dict1['cus_phone'] = i.cus_phone
            dict1['cus_create_person'] = None
            dict1['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
            dict1['now_status'] = i.now_status
            dict1['remark_describe'] = i.remark_describe
            list1.append(dict1)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})

# 约定书下拉框
def poll_list1(request):
    try:
        cus_list = models.Customers_poll_model.objects.filter(now_status=0)
        cus_count = models.Customers_poll_model.objects.count()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': e})
    list = []
    for i in cus_list:
        # 获取当前账户的id
        dict = {}
        dict['id'] = i.id
        dict['cus_audited_object'] = str(i.cus_audited_object+'/'+i.cus_code)
        list.append(dict)
    Result = {'code': 0, 'msg': '成功！', 'count': cus_count, 'data': list}
    return JsonResponse(Result)

# 申请修改页面
def poll_apply_view(request):
    return render(request, 'customers/apply.html')

@transaction.atomic
def poll_apply(request):
    cus_id = request.POST.get('id')  # 客户数据ID
    log_msg = request.POST.get('remark_describe')
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    # logs数据库中添加一条数据
    miaoshu = '' + request.user.user_code + '对' + Customers_poll_model.objects.get(
        id=cus_id).cus_audited_object + '申请修改客户信息'
    user_creator_id = Customers_poll_model.objects.get(id=cus_id).cus_created_person_id
    try:
        Customers_edit_model.objects.create(remark_describe=log_msg,log_tocus_id=cus_id,from_person_id=request.user.id,to_person_id=user_creator_id,touser_remark=miaoshu)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code':202,'msg':'日志添加出现问题！'})
    action.send(sender=request.user.id,msg=miaoshu,xiangshu=log_msg,to_user=user_creator_id)
    return JsonResponse({"code": 0, "msg": "申请成功！请等待处理！"})